package com.example.asyncio;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Author wangJinLong
 * Date 2025/8/18 14:03
 **/
public class DbApp {

    private static Map<String, DruidDataSource> map = new HashMap<>();

    public static DruidDataSource mysqlDataSource() {
        DruidDataSource dataSource = map.get("mysql");
        if (Objects.isNull(dataSource)) {
            DruidDataSource ds2 = druidSource();
            map.put("mysql", ds2);
            return ds2;
        }
        return dataSource;
    }

    private static DruidDataSource druidSource() {
        DruidDataSource ds2 = new DruidDataSource();
        // ✅ 完整的 JDBC URL
        ds2.setUrl("jdbc:mysql://106.54.174.109:13306/my_cdc?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&connectTimeout=5000&socketTimeout=30000");
        ds2.setUsername("root");
        ds2.setPassword("mysql@123456");
        ds2.setDriverClassName("com.mysql.jdbc.Driver");

        // 连接池配置
        ds2.setInitialSize(2);
        ds2.setMinIdle(5);
        ds2.setMaxActive(10);
        return ds2;
    }

    public static Db getMysqlDb() {
        return Db.use(mysqlDataSource());
    }

    public static void main(String[] args) throws SQLException {
        Entity first = getMysqlDb().query("select * from spend_report where featuresId = ? limit 1", "14901")
                .getFirst();
        String featureId = first.getStr("featuresId");
        System.out.println("featureId: " + featureId);
    }

    private static void extracted1() throws SQLException {
        Entity first = Db.use().query("select * from spend_report where featuresId = ? limit 1", "14901")
                .getFirst();
        String featureId = first.getStr("featuresId");
        System.out.println("featureId: " + featureId);
    }

    private static void extracted2() throws SQLException {
        DataSource druid = DSFactory.get("ds1");
        System.out.println(druid.getConnection());

        Db db = Db.use(druid);
        Entity first = db.query("select * from spend_report where featuresId = ? limit 1", "14901")
                .getFirst();

        String featureId = first.getStr("featuresId");
        System.out.println("featureId: " + featureId);
    }

    public static void druidDb() throws SQLException {
        DruidDataSource ds2 = druidSource();

        Db db = Db.use(ds2);

        Entity first = db.query("select * from spend_report where featuresId = ? limit 1", "14901")
                .getFirst();

        String featureId = first.getStr("featuresId");
        System.out.println("featureId: " + featureId);
    }
}
